﻿using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using BLL;
using DAL;
using Ext.Net;
using Roles;

namespace ERP.Page
{
    public partial class MainSystem : MasterPage
    {
        #region[Define]
        private DataTable _dtGetUserInfo;
        private DataTable _dtGetUser;
        private readonly BllUser _clsUser = new BllUser();
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["login"] == null && Session["UserName"] == null)
            {
                Response.Redirect(@"../Login.aspx");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
                Response.Cache.SetNoStore();
            }
            else
            {
                if ((bool)Session["login"] == false)
                {
                    Response.Redirect(@"../Login.aspx");
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
                    Response.Cache.SetNoStore();
                }
                else
                {
                    CheckPermisstion();
                    SetCurrentPage();
                    btnSystems.Text = Session["UserName"].ToString();
                }
            }
        }
        //Button
        protected void btnChangePass_Click(object sender, DirectEventArgs e)
        {
            if (String.IsNullOrEmpty(txtPassOld.Text) && String.IsNullOrEmpty(txtNewPass.Text) &&
                String.IsNullOrEmpty(txtConfirmPasswords.Text))
            {
                HTML.clsFormat.Alert_ERROR("Thông Báo", "Vui lòng điền vào đầy đủ thông tin để thay đổi mật khẩu !");
            }
            else
            {
                ChangePass();
            }
        }
        protected void btnCancel_Click(object sender, DirectEventArgs e)
        {
            WindowChangePass.Close();
        }
        protected void btnClose_Click(object sender, DirectEventArgs e)
        {
            WindowUserInfo.Close();
        }
        protected void btnCloseSoftInfo_Click(object sender, DirectEventArgs e)
        {
            WindowSoftInfo.Close();
        }
        //Menu
        protected void MenuItemUserInfo_Click(object sender, DirectEventArgs e)
        {
            GetUserInfo();
            WindowUserInfo.Show();
        }
        protected void MenuItemChangePage_Click(object sender, DirectEventArgs e)
        {
            txtPassOld.Text = string.Empty;
            txtNewPass.Text = string.Empty;
            txtConfirmPasswords.Text = string.Empty;
            WindowChangePass.Show();
            txtPassOld.Focus(false, 100);
        }
        protected void MenuItemExit_Click(object sender, DirectEventArgs e)
        {
            try
            {
                var path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/");
                var obj = new EtUser { UsersId = int.Parse(Session["Users_Id"].ToString()) };
                BllUser.UpdateLastLogin(obj);
                if (File.Exists(path + "Session.xml"))
                    File.Delete(path + "Session.xml");
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
           
            var cookie = Request.Cookies["login"];
            if (cookie != null)
            {
                Session["login"] = false;
                Session.RemoveAll();
                Session.Abandon();

                cookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(cookie);
                Response.Redirect(@"../Login.aspx");
            }
            else
            {
                Session["login"] = false;
                Session.RemoveAll();
                Session.Abandon();
                Response.Redirect(@"../Login.aspx");
            }
        }
        protected void MenuItemAbout_Click(object sender, DirectEventArgs e)
        {
            WindowSoftInfo.Show();
            GetLicense();
        }
        protected void MenuSystems_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"Sys.aspx");
        }
        protected void MenuBuy_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"Buy.aspx");
        }
        protected void MenuSell_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"Sell.aspx");
        }
        protected void MenuReceipt_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"Receipt.aspx");
        }
        protected void MenuWareHouse_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"Warehouse.aspx");
        }
        protected void MenuCompany_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"Company.aspx");
        }
        protected void MenuKeToan_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"Accounting.aspx");
        }
        protected void MenuCustomer_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"Customer.aspx");
        }
        protected void MenuDichVu_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"Service.aspx");
        }
        protected void MenuEmployee_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"Employee.aspx");
        }
        protected void MenuChotSoThuChi_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"ReportReceipt.aspx");
        }
        protected void MenuReport_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect(@"ReportManager.aspx");
        }
        #endregion

        #region[Method]
        private void GetUserInfo()
        {
            _dtGetUserInfo = _clsUser.GetUserEdit(int.Parse(Session["Users_Id"].ToString()));
            if (_dtGetUserInfo != null && _dtGetUserInfo.Rows.Count > 0)
            {
                lbUserName.Text = _dtGetUserInfo.Rows[0]["UserName"].ToString();
                lbFullName.Text = _dtGetUserInfo.Rows[0]["FullName"].ToString();
                lbJob.Text = _dtGetUserInfo.Rows[0]["Job_Name"].ToString();
                lbRoles.Text = _dtGetUserInfo.Rows[0]["Group_Name"].ToString();
                lbCellPhone.Text = _dtGetUserInfo.Rows[0]["CellPhone"].ToString();
                lbEmail.Text = _dtGetUserInfo.Rows[0]["Email"].ToString();
                lbCreateDate.Text = String.Format("{0:dd/MM/yyyy}", _dtGetUserInfo.Rows[0]["CreatedDate"]);
            }
        }
        private void UpdatePass()
        {
            try
            {
                var obj = new EtUser
                {
                    UsersId = int.Parse(Session["Users_Id"].ToString()),
                    Passwords = Encode.Encode.GetMD5(txtConfirmPasswords.Text).ToUpper()
                };
                BllUser.ChangePass(obj);
                HTML.clsFormat.Alert_INFO("Thông Báo", "Thay đổi mật khẩu thành công !");
                WindowChangePass.Close();
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void ChangePass()
        {
            string oldpass = Encode.Encode.GetMD5(txtPassOld.Text);
            _dtGetUser = _clsUser.GetUserEdit(int.Parse(Session["Users_Id"].ToString()));
            if (_dtGetUser != null && _dtGetUser.Rows.Count > 0)
            {
                if (_dtGetUser.Rows[0]["Passwords"].ToString() != oldpass.ToUpper())
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Mật khẩu cũ không chính xác !");
                }
                else
                {
                    UpdatePass();
                }
            }
        }
        #endregion

        #region[CheckLicense]
        private void GetLicense()
        {
            var ClsLicense = new bll_sad_License();
            var dtGetLicense = ClsLicense.GetLicense();
            if (dtGetLicense != null && dtGetLicense.Rows.Count > 0)
            {
                lbCustomer.Text = dtGetLicense.Rows[0]["Customer"].ToString();
                lbLicenseTye.Text = dtGetLicense.Rows[0]["LicenseType"].ToString();
                lbLicense.Text = dtGetLicense.Rows[0]["License"].ToString();
                lbKey.Text = dtGetLicense.Rows[0]["Key"].ToString();
                lbCreateDateLicense.Text = String.Format("{0:dd/MM/yyyy}", dtGetLicense.Rows[0]["DateActived"]);
                lbVersion.Text = dtGetLicense.Rows[0]["Version"].ToString();
                lbStatustActive.Text = dtGetLicense.Rows[0]["StatusActived"].ToString();
            }
        }
        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                #region[Modules-Main]
                var Is_PageQuanTriHeThong = SecurityServices.HasPermisstionPageMain(StringContent.QuanTriHeThong, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageQuanTriHeThong == false)
                    {
                        MenuSystems.Visible = false;
                    }
                }
                var Is_PageMuaHang = SecurityServices.HasPermisstionPageMain(StringContent.MuaHang, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageMuaHang == false)
                    {
                        MenuBuy.Visible = false;
                    }
                }
                var Is_PageBanHang = SecurityServices.HasPermisstionPageMain(StringContent.BanHang, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageBanHang == false)
                    {
                        MenuSell.Visible = false;
                    }
                }
                var Is_PageReceipt = SecurityServices.HasPermisstionPageMain(StringContent.QuanLyCongNo, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageReceipt == false)
                    {
                        MenuReceipt.Visible = false;
                    }
                }
                var Is_PageWareHouse = SecurityServices.HasPermisstionPageMain(StringContent.QuanLyKho, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageWareHouse == false)
                    {
                        MenuWareHouse.Visible = false;
                    }
                }
                var Is_PageCustomer = SecurityServices.HasPermisstionPageMain(StringContent.KhachHang, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageCustomer == false)
                    {
                        MenuCustomer.Visible = false;
                    }
                }
                var Is_PageCompany = SecurityServices.HasPermisstionPageMain(StringContent.CongTy, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageCompany == false)
                    {
                        MenuCompany.Visible = false;
                    }
                }
                var Is_PageKeToan = SecurityServices.HasPermisstionPageMain(StringContent.KeToan, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageKeToan == false)
                    {
                        MenuKeToan.Visible = false;
                    }
                }
                var Is_PageDichVu = SecurityServices.HasPermisstionPageMain(StringContent.QuanLyDichVu, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageDichVu == false)
                    {
                        MenuDichVu.Visible = false;
                    }
                }
                var Is_PageEmployee = SecurityServices.HasPermisstionPageMain(StringContent.NhanVien, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageEmployee == false)
                    {
                        MenuEmployee.Visible = false;
                    }
                }
                var Is_PageChotSoThuChi = SecurityServices.HasPermisstionPageMain(StringContent.BaoCaoThongKe, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageChotSoThuChi == false)
                    {
                        MenuChotSoThuChi.Visible = false;
                    }
                }
                //var Is_PageReport = SecurityServices.HasPermisstionPageMain(StringContent.Report, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                //{
                //    if (Is_PageReport == false)
                //    {
                //        MenuReport.Visible = false;
                //    }
                //}
                var Is_PageTuDienKho = SecurityServices.HasPermisstionPageMain(StringContent.TuDienKho, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageTuDienKho == false)
                    {
                        PanelTuDienKho.Visible = false;
                    }
                }
                var Is_PageDanhMucChung = SecurityServices.HasPermisstionPageMain(StringContent.DanhMucChung, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageDanhMucChung == false)
                    {
                        PanelDanhMucChung.Visible = false;
                    }
                }
                #endregion

                #region[Modules-Parrent]
                var Is_PageBranch = SecurityServices.HasPermisstionPageParrent(StringContent.Branch, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageBranch == false)
                    {
                        ShowTabChiNhanh.Visible = false;
                    }
                }
                var Is_PageRoom = SecurityServices.HasPermisstionPageParrent(StringContent.Room, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageRoom == false)
                    {
                        ShowTabPhongChua.Visible = false;
                    }
                }
                var Is_PageWarehouse = SecurityServices.HasPermisstionPageParrent(StringContent.Warehouse, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageWarehouse == false)
                    {
                        ShowTabKho.Visible = false;
                    }
                }
                var Is_PageManufacturer = SecurityServices.HasPermisstionPageParrent(StringContent.Manufacturer, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageManufacturer == false)
                    {
                        ShowTabManufacturer.Visible = false;
                    }
                }
                var Is_PageUnit = SecurityServices.HasPermisstionPageParrent(StringContent.Unit, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageUnit == false)
                    {
                        ShowTabDVT.Visible = false;
                    }
                }
                var Is_PageMaterials_Type = SecurityServices.HasPermisstionPageParrent(StringContent.Materials_Type, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageMaterials_Type == false)
                    {
                        ShowTabNhomVatTu.Visible = false;
                    }
                }
                var Is_PageVatTu = SecurityServices.HasPermisstionPageParrent(StringContent.VatTu, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageVatTu == false)
                    {
                        ShowTabVatTu.Visible = false;
                    }
                }
                var Is_PageEnterprise = SecurityServices.HasPermisstionPageParrent(StringContent.Enterprise, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageEnterprise == false)
                    {
                        ShowTabLoaiDoanhNghiep.Visible = false;
                    }
                }
                var Is_PageBank = SecurityServices.HasPermisstionPageParrent(StringContent.Bank, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageBank == false)
                    {
                        ShowTabNganHang.Visible = false;
                    }
                }
                var Is_PageEthnic = SecurityServices.HasPermisstionPageParrent(StringContent.Ethnic, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageEthnic == false)
                    {
                        ShowTabDanToc.Visible = false;
                    }
                }
                var Is_PageCurrency = SecurityServices.HasPermisstionPageParrent(StringContent.Currency, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageCurrency == false)
                    {
                        ShowTabTienTe.Visible = false;
                    }
                }
                var Is_PageNational = SecurityServices.HasPermisstionPageParrent(StringContent.National, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageNational == false)
                    {
                        ShowTabQuocGia.Visible = false;
                    }
                }
                var Is_PageDomain = SecurityServices.HasPermisstionPageParrent(StringContent.Domain, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageDomain == false)
                    {
                        ShowTabMien.Visible = false;
                    }
                }
                var Is_PageProvince = SecurityServices.HasPermisstionPageParrent(StringContent.Province, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageProvince == false)
                    {
                        ShowTabTinh.Visible = false;
                    }
                }
                var Is_PageDistricts = SecurityServices.HasPermisstionPageParrent(StringContent.Districts, int.Parse(Session["USer_Detail_Id"].ToString()), true);
                {
                    if (Is_PageDistricts == false)
                    {
                        ShowTabQuanHuyen.Visible = false;
                    }
                }
                #endregion
            }
        }
        #endregion

        #region[SetPageFocus]
        private void SetCurrentPage()
        {
            string pageName = GetPageName();

            switch (pageName)
            {
                case "Accounting.aspx":
                    PanelLeft.Title = "PHÂN HỆ KẾ TOÁN";
                    break;
                case "Buy.aspx":
                    PanelLeft.Title = "PHÂN HỆ MUA HÀNG";
                    break;
                case "Company.aspx":
                    PanelLeft.Title = "CÔNG TY";
                    break;
                case "Customer.aspx":
                    PanelLeft.Title = "PHÂN HỆ KHÁCH HÀNG";
                    break;
                case "Employee.aspx":
                    PanelLeft.Title = "NHÂN SỰ";
                    break;
                case "Receipt.aspx":
                    PanelLeft.Title = "PHÂN HỆ CÔNG NỢ";
                    break;
                case "ReportManager.aspx":
                    PanelLeft.Title = "BÁO CÁO QUẢN TRỊ";
                    break;
                case "ReportReceipt.aspx":
                    PanelLeft.Title = "CHỐT SỔ THU CHI";
                    break;
                case "Sell.aspx":
                    PanelLeft.Title = "PHÂN HỆ BÁN HÀNG";
                    break;
                case "Service.aspx":
                    PanelLeft.Title = "QUẢN LÝ DỊCH VỤ";
                    break;
                case "Sys.aspx":
                    PanelLeft.Title = "QUẢN LÝ HỆ THỐNG";
                    break;
                case "Warehouse.aspx":
                    PanelLeft.Title = "PHÂN HỆ KHO";
                    PanelTuDienKho.Visible = true;
                    break;
            }
        }
        private string GetPageName()
        {
            return Request.Url.ToString().Split('/').Last();
        }
        #endregion
    }
}